package com.ssh.admin.action;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.ssh.common.util.JsonResult;
import com.ssh.common.util.Page;
import com.ssh.entity.Brand;
import com.ssh.entity.Employee;
import com.ssh.entity.Product;
import com.ssh.entity.SuperMarket;
import com.ssh.entity.SuperMarketProduct;
import com.ssh.entity.Task;
import com.ssh.entity.TaskBrand;
import com.ssh.entity.TaskProductEmployee;
import com.ssh.manager.BrandManager;
import com.ssh.manager.EmployeeManager;
import com.ssh.manager.SuperMarketManager;
import com.ssh.manager.SuperMarketProductManager;
import com.ssh.manager.TaskBrandManager;
import com.ssh.manager.TaskManager;
import com.ssh.manager.TaskProductEmployeeManager;
@Controller
@ParentPackage("admin")
@Scope("prototype")
@Results(value={
@Result(name="success", location="/admin/taskProductEmployee/t_p_e_list.jsp"),
@Result(name="add", type="json", params={"root","jr","excludeproperties","jr\\.code"}),
@Result(name="delete", type="json", params={"root","page","excludeproperties","page\\.curPageNum"}),
@Result(name="findList", type="json", params={"root","page","excludeproperties","page\\.curPageNum,page\\.totalPageNum,page\\.totalCount," +
		"page\\.numberPerPage,page\\.pageData\\[\\d+\\]\\.id,page\\.pageData\\[\\d+\\]\\.startDate,page\\.pageData\\[\\d+\\]\\.endDate,page\\.pageData\\[\\d+\\]\\.createDate," +
		"page\\.pageData\\[\\d+\\]\\.taskBrand\\.task\\.content,page\\.pageData\\[\\d+\\]\\.taskBrand\\.brand\\.name,page\\.pageData\\[\\d+\\]\\.employee\\.userName," +
		"page\\.pageData\\[\\d+\\]\\.fenxiao,page\\.pageData\\[\\d+\\]\\.chenlie,page\\.pageData\\[\\d+\\]\\.duitou," +
		"page\\.pageData\\[\\d+\\]\\.superMarketProduct\\.superMarket\\.name,page\\.pageData\\[\\d+\\]\\.superMarketProduct\\.product\\.name,page\\.pageData\\[\\d+\\]\\.planStock"})
})
public class TaskProductEmployeeAction extends ActionSupport{
	@Resource(name="taskProductEmployeeManagerImpl")
	private TaskProductEmployeeManager taskProductEmployeeManager;
	@Resource(name="taskManagerImpl")
	private TaskManager taskManager;
	@Resource(name="brandManagerImpl")
	private BrandManager brandManager;
	@Resource(name="taskBrandManagerImpl")
	private TaskBrandManager taskBrandManager;
	@Resource(name="employeeManagerImpl")
	private EmployeeManager employeeManager;
	@Resource(name="superMarketManagerImpl")
	private SuperMarketManager superMarketManager;
	@Resource(name="superMarketProductManagerImpl")
	private SuperMarketProductManager superMarketProductManager;
	
	private JsonResult jr=new JsonResult();
	private Page page = new Page();
	private String isDesc;
	
	private TaskBrand taskBrand;
	private Task task;
	private Employee employee;
	private SuperMarket superMarket;
	private Brand brand;
	private Product product;
	private TaskProductEmployee taskProductEmployee;
	
	private String brandIds;
	private String superMarketIds;
	private String employeeIds;
	private String ids;
	
	public String getIds() {
		return ids;
	}
	public void setIds(String ids) {
		this.ids = ids;
	}
	public Employee getEmployee() {
		return employee;
	}
	public void setEmployee(Employee employee) {
		this.employee = employee;
	}
	public SuperMarket getSuperMarket() {
		return superMarket;
	}
	public void setSuperMarket(SuperMarket superMarket) {
		this.superMarket = superMarket;
	}
	public Brand getBrand() {
		return brand;
	}
	public void setBrand(Brand brand) {
		this.brand = brand;
	}
	public Product getProduct() {
		return product;
	}
	public void setProduct(Product product) {
		this.product = product;
	}
	public TaskProductEmployee getTaskProductEmployee() {
		return taskProductEmployee;
	}
	public void setTaskProductEmployee(TaskProductEmployee taskProductEmployee) {
		this.taskProductEmployee = taskProductEmployee;
	}
	public TaskBrand getTaskBrand() {
		return taskBrand;
	}
	public void setTaskBrand(TaskBrand taskBrand) {
		this.taskBrand = taskBrand;
	}
	public String getBrandIds() {
		return brandIds;
	}
	public void setBrandIds(String brandIds) {
		this.brandIds = brandIds;
	}
	public Task getTask() {
		return task;
	}
	public void setTask(Task task) {
		this.task = task;
	}
	public String getSuperMarketIds() {
		return superMarketIds;
	}
	public void setSuperMarketIds(String superMarketIds) {
		this.superMarketIds = superMarketIds;
	}
	public String getEmployeeIds() {
		return employeeIds;
	}
	public void setEmployeeIds(String employeeIds) {
		this.employeeIds = employeeIds;
	}
	public JsonResult getJr() {
		return jr;
	}
	public void setJr(JsonResult jr) {
		this.jr = jr;
	}
	public Page getPage() {
		return page;
	}
	public void setPage(Page page) {
		this.page = page;
	}
	public String getIsDesc() {
		return isDesc;
	}
	public void setIsDesc(String isDesc) {
		this.isDesc = isDesc;
	}
	
	public String goJsp(){
		return "success";
	}
	
	public String findList(){
		Map conditionMap = new HashMap();
		conditionMap.put("task", task.getContent());
		conditionMap.put("employee", employee.getId());
		conditionMap.put("market", superMarket.getName());
		conditionMap.put("brand", brand.getId());
		conditionMap.put("product", product.getId());
		
		taskProductEmployeeManager.findListBy(conditionMap, page, isDesc);
		return "findList";
	}
	
	public String updatePlan(){
		int p = taskProductEmployee.getPlanStock();
		taskProductEmployee = taskProductEmployeeManager.findTaskProductEmployeeEmployee(taskProductEmployee.getId());
		taskProductEmployee.setPlanStock(p);
		taskProductEmployeeManager.saveUpdate(taskProductEmployee);
		return "delete";
	}
	
	public String save(){
		try {
			//获取品牌、门店、业务员的组合字符串数组
			String[] brandStr = brandIds.split("-");
			//获取任务实体
			task = taskManager.fingTaskById(task.getId());
			for (int i = 0; i < brandStr.length; i++) {
				String str = brandStr[i];
				Long bid = new Long(str.substring(0, str.indexOf(";")));
				str = str.substring(str.indexOf(";")+1, str.length());
				String[] mEmps = str.split(";");
				String[] m = new String[mEmps.length];
				String[] e = new String[mEmps.length];
				for (int j = 0; j < mEmps.length; j++) {
					m[j] = mEmps[j].substring(0,mEmps[j].indexOf(","));
					e[j] = mEmps[j].substring(mEmps[j].indexOf(",")+1,mEmps[j].length());
				}
				//保存任务品牌
				TaskBrand tb = new TaskBrand();
				tb.setBrand(brandManager.getBrandById(bid));
				tb.setTask(task);
				tb.setCreateDate(new Date());
				tb.setDel(0);
				tb.setEndDate(new Date());
				tb.setStartDate(new Date());
				tb = taskBrandManager.saveUpdata(tb);
				//保存任务门店商品表
				for (int j = 0; j < m.length; j++) {
					//找出第j个门店的所有第i个品牌下的商品
					List<SuperMarketProduct> smpList = superMarketProductManager.findByMid_Bid(new Long(m[j]), bid);
					//获取门店及业务员实体
					superMarket = superMarketManager.getSuperMarketById(new Long(m[j]));
					employee = employeeManager.getById(new Long(e[j]));
					for (int k = 0; k < smpList.size(); k++) {
						TaskProductEmployee tpe = new TaskProductEmployee();
						tpe.setTaskBrand(tb);
						tpe.setEmployee(employee);
						tpe.setSuperMarketProduct(smpList.get(k));
						
						tpe.setPlanStock(taskProductEmployee.getPlanStock());
						tpe.setFenxiao(taskProductEmployee.getFenxiao());
						tpe.setChenlie(taskProductEmployee.getChenlie());
						tpe.setDuitou(taskProductEmployee.getDuitou());
						tpe.setStartDate(new Timestamp(System.currentTimeMillis()));
						tpe.setCreateDate(new Timestamp(System.currentTimeMillis()));
						tpe.setEndDate(new Timestamp(System.currentTimeMillis()));
						tpe.setDel(0);
						taskProductEmployeeManager.saveUpdate(tpe);
					}
				}
			}
			jr.setCode("y");
		} catch (Exception e) {
			jr.setCode("n");
			e.printStackTrace();
		}
		return "add";
	}
		
	public String add(){
		try {
			//获取品牌ID数组
			String[] b = brandIds.split(",");
			//获取任务实体
			task = taskManager.fingTaskById(task.getId());
			List<TaskBrand> tbs = new ArrayList<TaskBrand>();
			//保存任务品牌
			for (int i = 0; i < b.length; i++) {
				TaskBrand tb = new TaskBrand();
				tb.setBrand(brandManager.getBrandById(new Long(b[i])));
				tb.setTask(task);
				tb.setCreateDate(new Date());
				tb.setDel(0);
				tb.setEndDate(new Date());
				tb.setStartDate(new Date());
				tb = taskBrandManager.saveUpdata(tb);
				tbs.add(tb);
			}
			
			//获取门店跟业务员数组
			String[] m = superMarketIds.split(",");
			String[] e = employeeIds.split(",");
			//保存任务产品业务员表
			//门店循环
			for (int i = 0; i < m.length; i++) {
				//找出第i个门店的所有b品牌下的商品
				List<SuperMarketProduct> smpList = superMarketProductManager.findBysmId_brandId(new Long(m[i]), b);
				//找出门店匹配的业务员
				Employee emp = employeeManager.getById(new Long(e[i]));
				//根据门店商品保存
				//循环根据门店及所有品牌查出来的门店商品
				for (int j = 0; j < smpList.size(); j++) {
					//循环任务品牌
					for (int j2 = 0; j2 < tbs.size(); j2++) {
						TaskProductEmployee tpe = new TaskProductEmployee();
						tpe.setTaskBrand(tbs.get(j2));
						tpe.setEmployee(emp);
						tpe.setSuperMarketProduct(smpList.get(j));
						
						tpe.setStartDate(new Timestamp(System.currentTimeMillis()));
						tpe.setCreateDate(new Timestamp(System.currentTimeMillis()));
						tpe.setEndDate(new Timestamp(System.currentTimeMillis()));
						tpe.setPlanStock(taskProductEmployee.getPlanStock());
						tpe.setFenxiao(taskProductEmployee.getFenxiao());
						tpe.setChenlie(taskProductEmployee.getChenlie());
						tpe.setDuitou(taskProductEmployee.getDuitou());
						tpe.setDel(0);
						tpe.setEmployee(emp);
						try {
							taskProductEmployeeManager.saveUpdate(tpe);
						} catch (Exception e2) {
							e2.printStackTrace();
						}
					}
				}
			}
			jr.setCode("y");
		} catch (Exception e) {
			jr.setCode("n");
			e.printStackTrace();
		}
		return "add";
	}
	
	public String delete(){
		try {
			if(ids!=null && !ids.equals("")){
				String[] d = ids.split(",");
				for (int i = 0; i < d.length; i++) {
					taskProductEmployeeManager.delete(new Long(d[i]));
				}
			}else{
				taskProductEmployeeManager.delete(taskProductEmployee.getId());
			}
			int _p = (int) page.getCurPageNum();
			Map conditionMap = new HashMap();
			conditionMap.put("task", task.getContent());
			conditionMap.put("employee", employee.getId());
			conditionMap.put("market", superMarket.getName());
			conditionMap.put("brand", brand.getId());
			conditionMap.put("product", product.getName());
			taskProductEmployeeManager.findListBy(conditionMap, page, isDesc);
			if(_p<=page.getTotalPageNum()){
				page.setCurPageNum(_p);
			}else{
				page.setCurPageNum(_p-1);
			}
			jr.setCode("y");
		} catch (Exception e) {
			e.printStackTrace();
			jr.setCode("n");
		}
		return "delete";
	}
}
